package com.joy.web.common.controller;

import com.joy.common.model.ApiResponse;
import com.joy.web.base.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName: Login
 * @Description: 登录、登出相关 Controller
 * @Author: yjzhao
 * @Create: 2019-09-17  13:16
 **/
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {

    /**
     * 登录页面初始化
     * @return
     */
    @RequestMapping(value = {"", "/"})
    public String index() {
        return "pages/login";
    }

    /**
     * 用户登录动作
     * @return
     */
    @RequestMapping(value = {"/hashLogin"})
    @ResponseBody
    public ApiResponse hashLogin(String userNm, String userPwd, Boolean rememberMe) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userNm, userPwd);
        if (rememberMe != null) {
            token.setRememberMe(rememberMe);
        }

        ApiResponse apiResponse = ApiResponse.ofSuccMessage("");
        String error = "";
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            error = "没有此用户";
            apiResponse = ApiResponse.ofErrorMessage(error);
        } catch (IncorrectCredentialsException e) {
            error = "密码错误";
            apiResponse = ApiResponse.ofErrorMessage(error);
        } catch (LockedAccountException e) {
            error = "账号被锁定";
            apiResponse = ApiResponse.ofErrorMessage(error);
        } catch (ExcessiveAttemptsException e) {
            error = "密码错误次数太多";
            apiResponse = ApiResponse.ofErrorMessage(error);
        } catch (AuthenticationException e) {
            error = "其他错误";
            apiResponse = ApiResponse.ofErrorMessage(error);
            e.printStackTrace();
        }

        return apiResponse;
    }

    @RequestMapping(value = {"/logout"})
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    /**
     * @Description 短信验证码登录
     * @param phoneNo 手机号
     * @param code 短信验证码
     * @return
     * @Author yjzhao
     * @Date 2019/9/25 8:55
     **/
    @RequestMapping(value = {"/phoneNo"})
    public ApiResponse phoneNo(String phoneNo, String code) {
        //自定义  UsernamePasswordToken 进行收集验证码登录

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ApiResponse.ofSuccMessage("已为您重置密码，密码已发送至您手机.请登录系统");
    }
}
